from collections import OrderedDict

from django.db import models
from django_filters import rest_framework as filters

ALL_LOOKUPS = [
    'icontains',
    'gt',
    'lt',
    'gte',
    'lte',
    'in',
    'exact',
    'iregex',
    'isnull',
]


def get_all_model_fields(model):
    opts = getattr(model, "_meta")

    return [
        f
        for f in sorted(opts.fields + opts.many_to_many)
        if not isinstance(f, models.AutoField) and not (getattr(f.remote_field, "parent_link", False))
    ]


class AllLookupsFilter(filters.FilterSet):

    @classmethod
    def get_fields(cls):
        model = cls._meta.model
        model_fields = get_all_model_fields(model)
        # 一般字段
        fields = [(f.name, ALL_LOOKUPS) for f in model_fields if
                  not f.is_relation and f.get_internal_type().__str__() != 'JSONField']
        fields.append(('id', ['exact', 'in']))
        # 外键字段 并且不是多对多字段
        for field in model_fields:
            if field.is_relation and not field.many_to_many:
                relations = field.foreign_related_fields
                for relation in relations:
                    relation_name = relation.name
                    filed_name = field.name + '__' + relation_name
                    fields.append((filed_name, ['exact']))
        return OrderedDict(fields)


class AllLookupsFilterBackend(filters.DjangoFilterBackend):
    filterset_base = AllLookupsFilter

    # def filter_queryset(self, request, queryset, view):
    #     return super().filter_queryset(request, queryset, view)
